import sys
from typing import Optional
from feasytools import ArgChecker
from fplotkit import NetPlot, ReadOnlyStatistics

opers = {
    "trips": ("绘制出行时间直方图", "trip_hist", bool, ""),
    "load-accum": ("绘制充电站负荷堆积图", "cs_load_accum", bool, ""),
    "cs-curve": ("绘制充电站参数曲线图", "cs_curves", bool, ""),
    "cs-price": ("绘制充电站电价曲线图", "cs_prices", bool, ""),
    "ev-attrib": ("绘制车辆参数曲线图", "ev_atrrib", str, "  参数: EV参数名称,车辆ID"),
    "ev-route": ("绘制车辆运行轨迹图", "ev_route", str, "  参数: 车辆ID"),
    "gen-curve": ("绘制发电机参数曲线图", "gen_curves", bool, ""),
    "gen-total": ("绘制发电总参数曲线图", "gen_total", bool, ""),
    "gen-compare": ("绘制发电机功率比较图","gen_compare", bool, ""),
    "bus-curve": ("绘制母线参数曲线图", "bus_curves", bool, ""),
    "bus-total": ("绘制母线总参数曲线图", "bus_total", bool, ""),
}

HELP_STRING = "".join(
    [
        f"画图程序 - 使用帮助\n{sys.argv[0]} [-h] [--help] [-d <仿真结果目录>] [-v <车辆行程文件>] [-t <绘制起始时间>] ",
        " ".join([f"[--{k}{'' if v[3]=='' else ' <参数>'}]" for k, v in opers.items()]),
        "\n    h/help: 显示本帮助\n    d: 仿真结果目录, 默认为results\n    v: 车辆行程文件, 默认为vehicles.xml\n    t: 绘制起始时间, 默认86400\n",
        "\n".join([f"    {k}: {v[0]}{v[3]}" for k, v in opers.items()]),
    ]
)


def print_help(err_str=None):
    if err_str:
        print(err_str)
    print()
    print(HELP_STRING)
    sys.exit()


def plot_main(resdir:str,args:ArgChecker,silent:bool=False):
    trunc = args.pop_int("t", 86400)
    trips = args.pop_str("v", "12nodes/12nodes.veh.xml")
    nplt = NetPlot(ReadOnlyStatistics(resdir),trips,trunc,resdir + "/figures/")
    for k, v in opers.items():
        if v[2] == bool:
            if args.pop_bool(k):
                if not silent: print(v[0])
                getattr(nplt, v[1])()
        else:
            par = args.pop_str(k, "")
            if par != "":
                if not silent: print(v[0])
                getattr(nplt, v[1])(*par.split(","))


if __name__ == "__main__":
    args = ArgChecker()
    if len(args.keys()) == 0:
        try:
            from fgui import PlotBox
        except:
            print_help("无法启用GUI模块, 请使用命令行参数运行")
        PlotBox().mainloop()
        sys.exit()

    if args.pop_bool("h") or args.pop_bool("help"):
        print_help()

    resdir = args.pop_str("d", "results")
    plot_main(resdir,args)

    if len(args.values()) > 0:
        for key in args.keys():
            print_help(f"解析错误:存在非法参数'{key}'")
